package com.ctsi.commons.util.collections;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 大小<1退化为一般LinkedHashMap
 * 线程不安全
 * @author zhangjw
 * 
 * @param <K>
 * @param <V>
 */
public class JdkLRUMap<K, V> extends LinkedHashMap<K, V> {
	private int maxSize;

	public JdkLRUMap() {
		super();
		maxSize = -1;
	}

	public JdkLRUMap(int size) {
		this(size, 32);
	}

	public JdkLRUMap(int size, int initialCapacity) {
		this(size, initialCapacity, (float) .75);
	}

	public JdkLRUMap(int size, int initialCapacity, float loadFactor) {
		// lru 必须true
		super(initialCapacity, loadFactor, true);
		maxSize = size;
	}

	public JdkLRUMap(Map<? extends K, ? extends V> m) {
		super(m);
	}

	/**
	 * 设置最大大小
	 * 
	 * @param size
	 *            Max Size (as integer)
	 */
	public  void setMaxSize(int size) {
		this.maxSize = size;
	}
    @Override
	protected boolean removeEldestEntry(Map.Entry<K, V> entry) {
		if (maxSize < 1) {
			return false;
		}
		return size() > maxSize;

	}

    /**
     * 获取key位置
     * @param key
     * @return
     */
	public  int indexOf(K key) {
		int result = 0;
		Iterator<K> ki = super.keySet().iterator();
		while (ki.hasNext()) {
			K obj = ki.next();
			if (obj.equals(key)) {
				return result;
			}
			result++;
		}
		return -1;

	}
}
